package dev

import (
	"context"
	"encoding/json"
	"ez/apps/dev/auto/mc"
	"gitee.com/dreamwood/ez-go/db/mgo"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"time"
)

type EzModel struct {
	mgo.BaseDoc `bson:"-" json:"-"`
	Id          int64           `json:"id" bson:"id,omitempty"`
	App         string          `json:"app" bson:"app"`       //APP
	Dir         string          `json:"dir" bson:"dir"`       //域
	Name        string          `json:"name" bson:"name"`     //名称
	CnName      string          `json:"cnName" bson:"cnName"` //中文名称
	Fields      []*EzModelField `json:"fields" bson:"fields"` //字段
	CreateAt    time.Time       `json:"createAt" bson:"createAt"`
	UpdateAt    time.Time       `json:"updateAt" bson:"updateAt"`
	DeleteAt    *time.Time      `json:"deleteAt" bson:"deleteAt"`
}

func (this *EzModel) DocName() string { return "EzModel" }
func (this *EzModel) GetId() int64    { return this.Id }
func (this *EzModel) SetId(id int64)  { this.Id = id }
func (this *EzModel) Create() error {
	return this.GetFactory().Create(this)
}
func (this *EzModel) Replace() error {
	return this.GetFactory().Replace(this)
}
func (this *EzModel) Save() error {
	if this.Id == 0 {
		this.CreateAt = time.Now()
		this.UpdateAt = time.Now()
		return this.GetFactory().Create(this)
	} else {
		this.UpdateAt = time.Now()
		return this.GetFactory().Replace(this)
	}
}

// 伪删除
func (this *EzModel) Delete() error {
	return this.GetFactory().Delete(this)
}
func (this *EzModel) UnDelete() error {
	return this.GetFactory().UnDelete(this)
}

// 真删除
func (this *EzModel) Destroy() error {
	return this.GetFactory().Destroy(this)
}
func (this *EzModel) ToString() string {
	return string(this.ToBytes())
}
func (this *EzModel) ToBytes() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *EzModel) Serialize() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *EzModel) UnSerialize(data []byte) []byte {
	ez.Try(json.Unmarshal(data, this))
	return data
}
func (this *EzModel) LoadFields() {
	fields, _ := NewEzModelFieldCrud().FindBy(ss.M{"modelId": this.Id}, []string{"id"}, 0, 0)
	this.Fields = fields
}
func (this *EzModel) ClearRelationsBeforeSave() mgo.Doc {
	this.Fields = nil
	return this
}
func neverUsed_EzModel() {
	//导入ss包
	a := ss.M{}
	ez.Debug(a)
}

type EzModelAccessControl struct {
	Access  bool
	Message string
	Action  string //控制器Action,小写开头，如c,u,r,d
	Model   *EzModel
	Session *ez.Session
}

func NewEzModelAccessControl(model *EzModel, action string, session *ez.Session) *EzModelAccessControl {
	ctrl := &EzModelAccessControl{
		Access:  true,
		Model:   model,
		Action:  action,
		Session: session,
	}
	ez.DispatchToMany(mc.EzModelAccessControlEvent, ctrl, context.TODO())
	return ctrl
}
